package cn.com.hhrcw.enterprise.web;

import cn.com.hhrcw.enterprise.params.EnRecruitParams;
import cn.com.hhrcw.enterprise.service.EnterpriseService;
import cn.com.hhrcw.enterprise.vo.EnRecruitVO;
import cn.com.hhrcw.entity.EnRecruit;
import cn.com.hhrcw.entity.OpJob;
import cn.com.hhrcw.entity.PiInfo;
import cn.com.hhrcw.entity.SysUserDepart;
import cn.com.hhrcw.mapstruct.EnRecruitConvert;
import cn.com.hhrcw.service.*;
import cn.com.hhrcw.utils.SubjectUtils;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.base.entity.AttributesValueParams;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

/**
 * 招聘者信息
 *
 * @author gaoruiyi
 * @since 2020-11-06
 */
@RestController
@Slf4j
@RequestMapping("/en/enRecruit")
@Api(tags = "招聘者信息")
@Validated
@Deprecated
public class EnRecruitController extends JeecgController<EnRecruit, IEnRecruitService> {

    @Autowired
    private IEnRecruitService enRecruitService;

    @Autowired
    private EnRecruitConvert enRecruitConvert;

    @Autowired
    private ISysUserDepartService sysUserDepartService;

    @Autowired
    private IPiInfoService piInfoService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private IOpJobService jobService;

    @Autowired
    IOpDeliveryHistoryService historyService;


    /**
     * 分页列表查询
     *
     * @param params 请求参数
     * @return
     */
    @GetMapping(value = "/list")
    @AutoLog("招聘者信息-分页列表查询")
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    @PermissionData
    public Result<Page<EnRecruitVO>> list(EnRecruitParams params, HttpServletRequest request) {
        QueryWrapper<EnRecruit> queryWrapper = QueryGenerator.initQueryWrapper(enRecruitConvert.toEntity(params), request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        queryWrapper.eq("del_flag", false);
        if (StringUtils.isBlank(params.getField())) {
            queryWrapper.orderByDesc("create_time");
        } else {
            queryWrapper.orderBy(true, params.getSort(), toUnderlineName(params.getField()));
        }
        IPage<EnRecruit> page = enRecruitService.page(params.page(), queryWrapper);
        //分页结果转换器
        Function<EnRecruit, EnRecruitVO> fun = enRecruit -> {
            EnRecruitVO vo = enRecruitConvert.toVO(enRecruit);
            List<OpJob> jobCount = jobService.lambdaQuery().eq(OpJob::getDelFlag, false).eq(OpJob::getRecruitmentState, 0).eq(OpJob::getCreateBy, sysUser.getId()).list();
            vo.setOnlineJobCount(CollectionUtils.isEmpty(jobCount) ? 0 : jobCount.size());
            if (!CollectionUtils.isEmpty(jobCount)) {
                List<String> jobId = new ArrayList<>();
                jobCount.forEach(e -> {
                    jobId.add(e.getId());
                });
                Integer seven = historyService.seven(jobId);
            }

            return vo;
        };

        return Result.ok((Page) page.convert(fun));
    }

    /**
     * 根据id查询
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/queryById")
    @ApiOperation(value = "根据id查询", notes = "根据id查询")
    @PermissionData
    public Result<EnRecruitVO> queryById(String id) {
        EnRecruit enRecruit = enRecruitService.lambdaQuery().eq(EnRecruit::getId, id).eq(EnRecruit::getDelFlag, false).one();
        if (enRecruit == null) {
            throw new JeecgBootException("数据不存在");
        }
        return Result.ok(enRecruitConvert.toVO(enRecruit));
    }

    /**
     * 根据userid查询
     *
     * @param userId 数据id
     * @return
     */
    @GetMapping(value = "/queryByUserId")
    @PermissionData
    public Result<EnRecruitVO> queryByUserId(String userId) {
        EnRecruit enRecruit = enRecruitService.lambdaQuery().eq(EnRecruit::getUserId, userId).eq(EnRecruit::getDelFlag, false).one();
        EnRecruitVO enRecruitVO = new EnRecruitVO();
        if (enRecruit != null) {
            enRecruitVO = enRecruitConvert.toVO(enRecruit);
        }
        PiInfo piInfo = piInfoService.lambdaQuery().eq(PiInfo::getDelFlag, false).eq(PiInfo::getUserId, userId).one();
        if (piInfo == null) {
            throw new JeecgBootException("数据不存在");
        }
        enRecruitVO.setPhotoId(piInfo == null ? null : piInfo.getPhotoId());
        enRecruitVO.setUserName(piInfo == null ? null : piInfo.getName());
        enRecruitVO.setPhone(piInfo == null ? null : piInfo.getPhone());
        enRecruitVO.setMailbox(piInfo == null ? null : piInfo.getEmail());
        return Result.ok(enRecruitVO);
    }

    /**
     * 添加同事
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/add")
    @AutoLog("招聘者信息-添加")
    @ApiOperation(value = "添加同事", notes = "添加同事")
    @RequiresPermissions("enRecruit:add")
    public Result<?> add(@RequestBody @Valid EnRecruitParams params) {

        Result result = enterpriseService.addColleague(params);

        return result;
    }

    /**
     * 编辑
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/edit")
    @AutoLog("招聘者信息-编辑")
    @ApiOperation(value = "编辑", notes = "编辑")
    @RequiresPermissions("enRecruit:edit")
    public Result<?> edit(@RequestBody @Valid EnRecruitParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        EnRecruit enRecruit = enRecruitConvert.toEntity(params);
        enRecruit.setUserId(sysUser.getId());
        boolean updated;
        LambdaUpdateWrapper<PiInfo> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(PiInfo::getUserId, sysUser.getId()).eq(PiInfo::getDelFlag, false).set(PiInfo::getPhotoId, params.getPhotoId()).set(PiInfo::getName, params.getUserName()).set(PiInfo::getPhone, params.getPhone()).set(PiInfo::getEmail, params.getMailbox()).set(PiInfo::getUpdateBy, sysUser.getUsername()).set(PiInfo::getUpdateTime, DateUtil.date());
        piInfoService.update(updateWrapper);

        enRecruit.setCreateBy(sysUser.getId());
        enRecruit.setCreateTime(DateUtil.date());
        enRecruit.setDelFlag(false);
        enRecruit.setUpdateBy(sysUser.getId());
        enRecruit.setUpdateTime(DateUtil.date());
        updated = enRecruitService.saveOrUpdate(enRecruit);

        return updated ? Result.ok() : Result.error("编辑失败");
    }

    /**
     * 删除同事
     *
     * @param params
     * @return
     */
    @PostMapping(value = "/deleteColleague")
    @AutoLog("招聘者信息-删除同事")
    @ApiOperation(value = "删除同事", notes = "删除同事")
    @RequiresPermissions("enRecruit:delete")
    public Result<?> deleteColleague(@RequestBody @Valid EnRecruitParams params) {
        LoginUser sysUser = (LoginUser) SubjectUtils.getSubject();
        QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", params.getUserId()).eq("dep_id", params.getCompanyId());
        boolean removed = sysUserDepartService.remove(queryWrapper);

        PiInfo piInfo = piInfoService.lambdaQuery().eq(PiInfo::getDelFlag, false).eq(PiInfo::getUserId, params.getUserId()).one();
        String type = piInfo.getRoleType().replace(",1", "").replace("1,", "").replace("1", "");
        LambdaUpdateWrapper<PiInfo> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.in(PiInfo::getUserId, params.getUserId()).eq(PiInfo::getDelFlag, false).set(PiInfo::getRoleType, type).set(PiInfo::getUpdateBy, sysUser.getUsername()).set(PiInfo::getUpdateTime, DateUtil.date());
        piInfoService.update(updateWrapper);

        return removed ? Result.ok() : Result.error("删除失败");
    }

    /**
     * 批量删除
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/delete")
    @AutoLog("招聘者信息-批量删除")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @RequiresPermissions("enRecruit:delete")
    public Result delete(String[] id) {
        LoginUser sysUser = (LoginUser) SubjectUtils.getSubject();
        LambdaUpdateWrapper<EnRecruit> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.in(EnRecruit::getId, id).set(EnRecruit::getDelFlag, true).set(EnRecruit::getUpdateBy, sysUser.getUsername()).set(EnRecruit::getUpdateTime, DateUtil.date());

        boolean deleted = enRecruitService.update(updateWrapper);
        return deleted ? Result.ok() : Result.error("删除失败");
    }

    /**
     * 属性值是否重复
     *
     * @return
     */
    @Override
    @GetMapping("/propertyRepeat")
    @ApiOperation(value = "属性值是否重复", notes = "属性值是否重复")
    public Result propertyIsRepeat(@Valid AttributesValueParams params) {
        return super.propertyIsRepeat(params);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param params
     */
    @SneakyThrows
    @GetMapping(value = "/exportXls")
    @ApiOperation(value = "导出excel", notes = "导出excel")
    public Result exportXls(HttpServletRequest request, EnRecruitParams params) {
        EnRecruit enRecruit = enRecruitConvert.toEntity(params);
        enRecruit.setDelFlag(false);
        QueryWrapper<EnRecruit> queryWrapper = QueryGenerator.initQueryWrapper(enRecruit, request.getParameterMap());
        List<EnRecruit> data = enRecruitService.list(queryWrapper);
        ExportParams exportParams = new ExportParams("招聘者信息", "招聘者信息");
        String url = super.exportXls(exportParams, EnRecruitVO.class, enRecruitConvert.toVO(data));
        return Result.ok((Object) url);
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/importExcel")
    @ApiOperation(value = "通过excel导入数据", notes = "通过excel导入数据")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, EnRecruit.class);
    }

}
